package DataStructureAndAlgorithm.CSP.Day06;
//有向图的强连通分量
import java.util.Scanner;
public class AcWing_3220 {
    static int N = 10010;
    static int M = 100010;
    static int n,m;
    static int[] h = new int [N];
    static int[] e = new int[M];
    static int[] ne = new int[M];
    static int idx = 0;
    static int[] dfn = new int[N];
    static int[] low = new int[N];
    static int[] stk = new int[N];
    static int top,ts;
    static boolean[] in_stk = new boolean[N];
    static int ans = 0;
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        m = in.nextInt();
        for (int i = 0;i < N; i++)h[i] = -1;
        for (int i = 0; i < m; i++){
            int a = in.nextInt();
            int b = in.nextInt();
            add(a,b);
        }

        for (int i = 1; i <= n; i++){
            if (dfn[i] == 0){
                tarjan(i);
            }
        }
        System.out.print(ans);

    }

    static void tarjan(int u){
        dfn[u] = ++ts;
        low[u] = ts;
        stk[ ++ top] = u;
        in_stk[u] = true;
        for (int i = h[u]; i != -1; i = ne[i]){
            int j = e[i];
            if (dfn[j] == 0){
                tarjan(j);
                low[u] = Math.min(low[u],low[j]);
            }else if(in_stk[j]){
                low[u] = Math.min(low[u],dfn[j]);
            }
        }

        if (dfn[u] == low[u]){
            int y,cnt = 0;
            do{
                y = stk[top--];
                in_stk[y] = false;
                cnt ++;
            }while (y != u);
            ans += cnt * (cnt - 1) / 2;
        }
    }

    static void add(int a,int b){
        e[idx] = b;
        ne[idx] = h[a];
        h[a] = idx++;
    }
}
